import React from 'react';
import PageTitle from 'component/page-title/index.jsx';
import { Link } from 'react-router-dom';
import CategorySelector from './category-selector.jsx';
import FileUploader from 'util/file-upload/index.jsx';
import MUtil from 'util/mm.jsx';
const _mm = new MUtil();
import './save.scss';
import RichEditor from 'util/rich-editor/index.jsx';
import Product from 'service/product-service.jsx';
const _product = new Product();

class ProductSave extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            id: this.props.match.params.pid,
            name: '',//商品名称
            subtitle: '',//商品描述
            price: '',//价格
            stock: '',//库存
            detail: '',//详细描述
            status: 1,//商品状态 1为在售
            categoryId: 0,
            parentCategoryId: 0,
            subImages: []
        }
    }
    //加载它
    componentDidMount() {
        this.loadProduct();

    }
    loadProduct() {

        //如果有id就回填出来
        if (this.state.id) {
            _product.getProduct(this.state.id).then((res) => {
                let images = res.subImages.split(',')
                res.subImages = images.map((item) => {
                    return {
                        uri: item,
                        url: res.imageHost + item
                    }
                })
                res.defaultDetail = res.detail

                this.setState({
                    name: res.name,
                    subtitle: res.subtitle,
                    price: res.price,
                    stock: res.stock,
                    defaultDetail: res.defaultDetail,
                    detail: res.detail,
                    categoryId: res.categoryId,
                    parentCategoryId: res.parentCategoryId,
                    subImages: res.subImages

                })
            })


        }
    }
    //简单字段的改变，比如商品名称、描述、价格、库存
    onValueChange(e) {
        let name = e.target.name
        let value = e.target.value.trim()
        this.setState({
            [name]: value
        })
    }
    //品类选择器的变化
    onCategoryChange(categoryId, parentCategoryId) {
        this.setState({
            categoryId: categoryId,
            parentCategoryId: parentCategoryId
        })
    }


    //上传图片之后的处理
    onUpLoadSuccess(res) {
        let subImages = this.state.subImages;
        subImages.push(res);
        this.setState({
            subImages: subImages
        })
    }

    //删除图片
    onImageDelete(e) {
        let index = e.target.getAttribute('index'),
            subImages = this.state.subImages;
        subImages.splice(index, 1);
        this.setState({
            subImages: subImages
        })

    }

    //富文本编辑器的变化
    onDetailValueChange(value) {

        this.setState({
            detail: value
        })
    }

    //上传图片失败
    onUploadError(error) {
        _mm.errTips(error.message || '上传图片失败')
    }
    subImagesString(data) {
        return this.state.subImages.map((image) => image.uri).join(',');
    }

    //提交表单
    onSubmit() {

        let product = {
            name: this.state.name,
            subtitle: this.state.subtitle,
            categoryId: parseInt(this.state.categoryId),
            subImages: this.subImagesString(), //images先处理成字符串那种格式
            detail: this.state.detail,
            price: parseFloat(this.state.price),
            stock: parseInt(this.state.stock),
            status: this.state.status
        }

        let productCheckResult = _product.checkProduct(product);
        if (this.state.id) {
            product.id = this.state.id;
        }
        //表单验证成功
        if (productCheckResult.status) {
            _product.saveProduct(product).then((res) => {

                _mm.successTips('新增产品成功！');
                this.props.history.push('/product/index');
            }, (errMsg) => {
                _mm.errTips(errMsg)
            });
        }
        // 表单验证失败
        else {
            _mm.errTips(productCheckResult.msg);
        }
    }
    render() {
        const { name, subtitle, subImages, categoryId, parentCategoryId, detail, defaultDetail, price, stock } = this.state
        return (
            <div id='page-wrapper'>
                <div className='row'>
                    <div className='col-md-12'>
                       { this.state.id ? <PageTitle title='编辑商品列表' /> : <PageTitle title='添加商品列表' />} 
                        
                        
                    </div>
                </div>
                <div className="form-horizontal">
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品名称</label>
                        <div className="col-sm-10">
                            <input type="email" name='name' value={name} onChange={(e) => this.onValueChange(e)} className="form-control" id="inputEmail3" placeholder="请输入商品名称" />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品描述</label>
                        <div className="col-sm-10">
                            <input type="email" value={subtitle} name='subtitle' onChange={(e) => this.onValueChange(e)} className="form-control" id="inputEmail3" placeholder="请输入商品名称" />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">所属分类</label>
                        <CategorySelector categoryId={categoryId} parentCategoryId={parentCategoryId} onCategoryChange={(categoryId, parentCategoryId) => this.onCategoryChange(categoryId, parentCategoryId)} />
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品价格</label>
                        <div className="col-sm-10">
                            <input type="email" name='price' value={price} onChange={(e) => this.onValueChange(e)} className="form-control" id="inputEmail3" placeholder='价格' />
                            <div className="input-group-addon">元</div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品库存</label>
                        <div className="col-sm-10">
                            <input type="email" value={stock} name='stock' onChange={(e) => this.onValueChange(e)} className="form-control" id="inputEmail3" placeholder='库存' />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className='col-sm-2 control-label'>商品图片</label>
                        <div className='col-sm-10'>
                            {subImages.length ? subImages.map((image, index) =>
                                <div className='img-con' key={index}>
                                    <img className='img' src={image.url} />
                                    <i className='fa fa-close' index={index} onClick={e => this.onImageDelete(e)}></i>
                                </div>

                            ) : <div>请上传图片</div>}
                        </div>
                        <div className='col-md-offset-2 col-sm-10 file-upload-con' >
                            <FileUploader onSuccess={(res) => this.onUpLoadSuccess(res)} onError={(err) => this.onUploadError(err)} />
                        </div>
                    </div>
                    <div className='form-group'>
                        <label className='col-md-2 control-label'>商品详情</label>
                        <div className='col-md-10'>
                            <RichEditor name='detail'
                                detail={this.state.detail}
                                defaultDetail={this.state.defaultDetail}
                                onChange={(e) => this.onValueChange(e)}
                                onValueChange={(value) => this.onDetailValueChange(value)} />
                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-sm-offset-2 col-sm-10">
                            <button type="submit" className="btn btn-primary" onClick={() => this.onSubmit()}>提交</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
export default ProductSave